package com.gable.exhibition.controller;

import com.alibaba.fastjson.JSON;
import com.gable.common.util.CacheData;
import com.gable.common.util.ImportExcel;
import com.gable.common.util.ReturnResultUtil;
import com.gable.common.util.StringUtil;
import com.gable.exhibition.model.Device;
import com.gable.exhibition.model.User;
import com.gable.exhibition.service.DeviceService;
import com.gable.exhibition.service.SequenceService;
import com.gable.exhibition.util.CheckImportExcelDevice;
import com.gable.exhibition.util.CheckImportExcelHospital;
import com.gable.exhibition.util.MessageUtil;
import com.gable.exhibition.view.*;
import com.gable.exhibition.websocket.WSClientManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Lesson on 2018/1/4.
 */
@Controller
@RequestMapping(value="/device")
public class DeviceController {

    Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    DeviceService deviceService;

    @Autowired
    CheckImportExcelDevice checkImportExcelDevice;

    @Autowired
    SequenceService sequenceService;


    /*@Autowired
    WSClientManager wsClientManager;*/

    @RequestMapping(value = "/page")
    public String page(HttpServletRequest request, HttpServletResponse response){
        try{
            //wsClientManager.sendMessage("dsjjdshjkdhsajhjdska");
        }catch (Exception e){
            e.printStackTrace();
        }
        return "device/device-page";
    }

    @RequestMapping(value="/info")
    public String info(HttpServletRequest request, HttpServletResponse response, @RequestParam(required = true) Long id){
        request.setAttribute("id",id);
        return "device/device-info";
    }

    @RequestMapping(value="/stationsEarch")
    public String stationsEarch(HttpServletRequest request, HttpServletResponse response){
        return "device-search";
    }


    @RequestMapping(value = "/queryDeviceList",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil queryDeviceList(HttpServletRequest request, HttpServletResponse response, DeviceView deviceView){
        try{
            Long userId = deviceView.getUserId();
            UserView sessionUser = CacheData.getSessionUser(userId, 1);
            if(sessionUser == null)
                return new ReturnResultUtil(600,MessageUtil.SESSIONNOTEXITIS);

            //医院登录
            if(sessionUser.getType().intValue() == 1101)
                deviceView.setHospitalId(sessionUser.getHospitalId());
            ReturnResultUtil rru = deviceService.queryDeviceList(deviceView);
            logger.info(JSON.toJSONString(rru));
            return  rru;
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ReturnResultUtil(500, MessageUtil.QUERYEXCEPTION);
    }

    @RequestMapping(value="/addOrUpdateDevice",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil addOrUpdateDevice(HttpServletRequest request, HttpServletResponse response, DeviceView deviceView){
        try{

            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            User user = CacheData.getSessionUser(deviceView.getUserId(),1);
            if(deviceView.getDeviceId() == null){
                deviceView.setCreatePerson(user.getUserId());
                deviceView.setCreateTime(df.format(new Date()));
            }else{
                deviceView.setUpdateDate(df.format(new Date()));
                deviceView.setUpdatePerson(user.getUserId());
            }
            //无设备保修新增设备时，默认设备状态为无效
            if(deviceView.getIsDel()==null){
                deviceView.setIsDel(0);
            }

            return deviceService.addOrUpdateDevice(deviceView);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ReturnResultUtil(500,MessageUtil.SAVEEXCEPTION);
    }

    @RequestMapping(value="/queryDeviceInfo",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil queryDeviceInfo(HttpServletRequest request, HttpServletResponse response){
        try{
            if(StringUtil.isEmpty(request.getParameter("deviceId"))){
                return  new ReturnResultUtil(500,MessageUtil.DEVICEIDISNULL);
            }
            Long deviceId = Long.parseLong(request.getParameter("deviceId"));
            ReturnResultUtil rru = deviceService.queryDeviceInfo(deviceId);
            logger.info(JSON.toJSONString(rru));
            return rru;
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ReturnResultUtil(500,MessageUtil.QUERYEXCEPTION);
    }

    @RequestMapping(value="/importDevice")
    public String importDevice(HttpServletRequest request, HttpServletResponse response){
        return "device/device-import";
    }

    @RequestMapping(value="/deviceExcel",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil deviceExcel(HttpServletRequest request,HttpServletResponse response){
        {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            List<MultipartFile> files = multipartRequest.getFiles("files");
            String rootPath = request.getSession().getServletContext().getRealPath(File.separator);
            try {
                Long ym = new Date().getTime();
                String filePath = "upload/" + ym;
                if (files != null && files.size() > 0) {
                    for (MultipartFile m : files) {
                        if (m.getBytes().length == 0) {
                            return new ReturnResultUtil(500, MessageUtil.PLEASEUPLOADFILE);
                        }
                        String suffix = m.getOriginalFilename().substring(m.getOriginalFilename().lastIndexOf(".") + 1);
                        if (!suffix.equals("xlsx")) {
                            return new ReturnResultUtil(500, MessageUtil.FILEFORMATWRONG);
                        }
                        filePath = filePath + suffix;
                        File file = new File(rootPath + filePath);
                        if (file.exists()) {
                            file.delete();
                            file.mkdirs();
                        } else {
                            file.mkdirs();
                        }
                        m.transferTo(file);
                    }
                    User user = CacheData.getSessionUser(null,1);
                    List<Object> list = ImportExcel.excelRead(rootPath + filePath, CheckImportExcelDevice.properties, ImportExcelDeviceModel.class);
                    CheckImportExcelDevice.resultMap.put(user.getUserId(), list);
                    logger.info("==================" + JSON.toJSONString(list));
                    return new ReturnResultUtil(200, MessageUtil.UPLOADSUCCESS, list);

                } else {
                    return new ReturnResultUtil(500, MessageUtil.UPLOADFILESERROR);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            return  new ReturnResultUtil(500,MessageUtil.UPLOADEXCEPTION);
        }
    }

    @RequestMapping(value="/checkExcelDevice",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil checkExcelDevice(HttpServletRequest request,HttpServletResponse response){
        ImportExcelView importExcelView = new ImportExcelView();
        try {
            User user = CacheData.getSessionUser(null,1);
            List<ImportExcelDeviceModel> list =(List<ImportExcelDeviceModel>)CheckImportExcelDevice.resultMap.get(user.getUserId());
            importExcelView = checkImportExcelDevice.checkImportExcelDevice(list,user);
            return new ReturnResultUtil(200,MessageUtil.EXAMINESUCCESS,importExcelView);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ReturnResultUtil(500,MessageUtil.EXAMINEERROR);
    }

    @RequestMapping(value="/saveDeviceByExecl",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil saveDeviceByExecl(HttpServletRequest request,HttpServletResponse response){
        try {
            User user = CacheData.getSessionUser(null, 1);
            List<ImportExcelDeviceModel> list = (List<ImportExcelDeviceModel>) CheckImportExcelDevice.resultMap.get(user.getUserId());
            ReturnResultUtil rru = deviceService.saveDeviceByExcel(list,user);
            CheckImportExcelDevice.resultMap.remove(user.getUserId());
            return rru;
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ReturnResultUtil(500,MessageUtil.SAVEEXCEPTION);
    }

    @RequestMapping(value="/searchDevice")
    public String searchPage(HttpServletRequest request){
        String keyword = request.getParameter("keyword");
        request.setAttribute("keyword",keyword);
        return "device-search";
    }

    @RequestMapping(value="/queryDeviceByKeyword",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil queryDeviceByKeyword(HttpServletRequest request){

        try {
            Long userId = null;
            if(!StringUtil.isEmpty(request.getParameter("userId"))){
                userId = Long.parseLong(request.getParameter("userId"));
            }

            User user =CacheData.getSessionUser(userId,1);
            Map map = new HashMap();
            map.put("hospitalId",user.getHospitalId());

            if(StringUtil.isEmpty(request.getParameter("keyword"))){
                return new ReturnResultUtil(500,MessageUtil.KEYWORDISNULL);
            }
            String keyword = request.getParameter("keyword");
            map.put("keyword",keyword);
            ReturnResultUtil rru = deviceService.queryDeviceByKeyword(map);
            logger.info(JSON.toJSONString(rru));
            return rru;
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ReturnResultUtil(500,MessageUtil.QUERYEXCEPTION);
    }



    @RequestMapping(value="/getQrcode",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil getQrcode(HttpServletRequest request, HttpServletResponse response,Long hospitalId){
        try{
            if(hospitalId==null){
                return  new ReturnResultUtil(500,MessageUtil.HSOPITALIDDOESTNOEXIST);
            }
            String qrcode = sequenceService.getQrcode(hospitalId);
            ReturnResultUtil rru = new ReturnResultUtil(200,MessageUtil.QUERYSUCCESS,qrcode);
            logger.info(JSON.toJSONString(rru));
            return rru;
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ReturnResultUtil(500,MessageUtil.QUERYEXCEPTION);
    }
}
